<template>
  <el-main>
    <el-row :gutter="40">
      <!-- 登录卡片 -->
      <el-col :span="8" :offset="8">
        <el-card style="margin-top: 60px" v-if="!showRegister">
          <h2 style="text-align: center; color: #008800">登录</h2>
          <el-form
              label-position="left"
              label-width="70px"
              :model="user"
              :rules="loginRules"
              ref="loginFormRef"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                  placeholder="请输入用户名"
                  v-model="user.username"
                  clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                  placeholder="请输入密码"
                  show-password
                  v-model="user.password"
                  @keyup.enter="login"
              ></el-input>
            </el-form-item>
            <el-form>
              <el-form-item prop="role">
                <el-radio-group v-model="user.role">
                  <el-radio label="user">普通用户</el-radio>
                  <el-radio label="admin">管理员</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button
                    type="primary"
                    style="width: 100%;
                             background-color: #35984b;
                             border: #35984b;
                             margin-top: 5px;
                             font-size: 16px; "
                    @click="login"
                    :loading="loading"
                >登录</el-button>
              </el-form-item>
            </el-form>
            <div style="color: #666; text-align: center; font-size: 14px; padding: 10px 0">
              没有账号？
              <a href="#" style="color: #008800; font-weight: bold;" @click.prevent="showRegister = true">立即注册</a>
            </div>
          </el-form>
        </el-card>

        <!-- 注册卡片 -->
        <el-card style="margin-top: 60px" v-else>
          <h2 style="text-align: center; color: #008800">注册</h2>
          <el-form
              label-position="left"
              label-width="80px"
              :model="reg"
              :rules="registerRules"
              ref="registerFormRef"
          >
            <el-form-item label="用户名" prop="username">
              <el-input placeholder="请输入用户名" v-model="reg.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入密码" show-password v-model="reg.password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input placeholder="请确认密码" show-password v-model="reg.confirmPassword"></el-input>
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
              <el-input placeholder="请输入电话号码" v-model="reg.phone"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="reg.gender" style="margin: 0;">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form>
              <el-form-item>
                <el-button
                    type="primary"
                    style="font-size: 16px; width: 100%; background-color: #35984b; border: #35984b; margin-top: 5px;"
                    @click="handleRegister"
                >立即注册</el-button>
              </el-form-item>
            </el-form>
            <div style="color: #666; text-align: center; font-size: 14px; padding: 10px 0">
              已有账号？
              <a href="#" style="color: #008800; font-weight: bold;" @click.prevent="showRegister = false">立即登录</a>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </el-main>
</template>

<script setup>
import {ref} from "vue";
import axios from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router";

const loginFormRef = ref(null);
const registerFormRef = ref(null);
const user = ref({
  username: '',
  password: '',
  role: 'user' // 默认选择普通用户
});
const showRegister = ref(false);
const loading = ref(false);
// 注册表单数据
const reg = ref({
  username: '',
  password: '',
  confirmPassword: '',
  gender: '',
  phone: '',
  role: 'user' // 默认角色为普通用户
});

// 登录验证规则
const loginRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur'}
  ],
  role: [
    {required: true, message: '请选择用户身份', trigger: 'change'}
  ]
};

// 注册验证规则
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度应为6-20位'));
  } else {
    if (reg.value.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword');
    }
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== reg.value.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号码'));
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

const registerRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, validator: validatePassword, trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, validator: validateConfirmPassword, trigger: 'blur'}
  ],
  phone: [
    {required: true, validator: validatePhone, trigger: 'blur'}
  ],
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ]
};

// 登录函数
const login = () => {
  loginFormRef.value.validate(valid => {
    if (!valid) return;

    loading.value = true;

    // 先检查用户是否存在
    axios.post('http://localhost:8080/v1/user/login', {
      username: user.value.username
    }).then((response) => {
      if (response.data.code == 4004) {
        ElMessage.error(response.data.msg);
        loading.value = false;
        return;
      }

      // 用户存在，进行登录
      axios.post('http://localhost:8080/v1/user/login', user.value)
          .then((response) => {
            if (response.data.code == 2000) {
              ElMessage.success('登录成功!');
              localStorage.setItem('user', JSON.stringify(response.data.data));
              // 根据角色跳转到不同页面
              if (user.value.role === 'admin') {
                router.push('/admin'); // 管理员跳转到管理员后台
              } else {
                router.push('/user'); // 普通用户跳转到用户端
              }
            } else {
              ElMessage.error(response.data.msg);
              loading.value = false;
            }
          })
          .catch((error) => {
            ElMessage.error('登录失败，请稍后重试');
            console.error(error);
            loading.value = false;
          });
    }).catch(error => {
      ElMessage.error('用户验证失败');
      console.error(error);
      loading.value = false;
    });
  });
};

// 注册函数
const handleRegister = () => {
  registerFormRef.value.validate(valid => {
    if (!valid) return;

    // 准备发送的数据
    const regData = {
      username: reg.value.username,
      password: reg.value.password,
      gender: reg.value.gender,
      phone: reg.value.phone,
      role: reg.value.role
    };

    // 发送注册请求
    axios.post('http://localhost:8080/v1/user/reg', regData)
        .then(response => {
          if (response.data.code == 2000) {
            ElMessage.success('注册成功！');
            // 清空注册表单
            reg.value = {
              username: '',
              password: '',
              confirmPassword: '',
              gender: '',
              phone: '',
              role: 'user'
            };
            // 跳转到登录部分
            showRegister.value = false;
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch(error => {
          ElMessage.error('注册失败，请稍后再试');
          console.error('注册错误:', error);
        });
  });
};

</script>

<style scoped>
.el-radio-group {
  width: 100%;
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #35984b;
  border-color: #35984b;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #35984b;
}

/* 输入框 */
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #008800 inset !important;
}

/* 单选框 */
:deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #008800 !important;
  background-color: #008800 !important;
}

/* 复选框 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  border-color: #008800 !important;
  background-color: #008800 !important;
}

/* 下拉框 */
:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #008800 inset !important;
  border-color: #008800 !important;
}
</style>